package com.zhiche.lisa.bms.service.sta.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.zhiche.lisa.bms.dao.mapper.sta.StaPriceMapper;
import com.zhiche.lisa.bms.dao.model.fee.FeePayable;
import com.zhiche.lisa.bms.dao.model.sta.StaPrice;
import com.zhiche.lisa.bms.enums.BaseEnum;
import com.zhiche.lisa.bms.pojo.dto.util.OtmServiceResult;
import com.zhiche.lisa.bms.pojo.vo.sta.StaPriceAndQuoteDtlVO;
import com.zhiche.lisa.bms.service.fee.FeePayableService;
import com.zhiche.lisa.bms.service.sta.AmgCstService;
import com.zhiche.lisa.bms.service.sta.StaPriceService;
import com.zhiche.lisa.bms.service.trans.TransTypeNameContrastService;
import com.zhiche.lisa.bms.service.utils.OtmUtil;
import com.zhiche.lisa.bms.service.utils.common.BeanColumnUtil;
import com.zhiche.lisa.core.supports.BaseException;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 标准价同步表 服务实现类
 * </p>
 *
 * @author liuanshun
 * @since 2018-10-23
 */
@Service
public class StaPriceServiceImpl extends ServiceImpl<StaPriceMapper, StaPrice> implements StaPriceService {
	@Autowired
	private AmgCstService amgCstService;

	@Autowired
	private TransTypeNameContrastService transTypeNameContrastService;

	@Autowired
	private FeePayableService feePayableService;

	@Autowired
	private OtmUtil otmUtil;

	/**
	 * 查询标准价同步分页数据
	 *
	 * @param pageParam
	 * @return
	 */
	@Override
	public Page<StaPrice> selectStaPricePage(Page<StaPrice> pageParam) {
		EntityWrapper<StaPrice> staPriceEntityWrapper = this.bindStaPriceWrapper(pageParam.getCondition());
		return selectPage(pageParam.setCondition(new HashMap<>()), staPriceEntityWrapper);
	}

	/**
	 * 获取标准价同步数据中的全部车型
	 *
	 * @return
	 */
	@Override
	public List<Object> selectAllStaPriceTransportNodeGid() {
		EntityWrapper<StaPrice> staPriceEntityWrapper = new EntityWrapper<>();
		staPriceEntityWrapper.isNotNull("transport_node_gid");
		staPriceEntityWrapper.groupBy("transport_node_gid");
		staPriceEntityWrapper.setSqlSelect("transport_node_gid");
		List<Object> list = selectObjs(staPriceEntityWrapper);
		if (list != null) {
			list.add(BaseEnum.BASE_TRANS_MODEL.getName());
		}
		return list;
	}

	private String spropertyToCloumnName(String type) {
		String cloumn = "";
		switch (type) {
			case "sLocZones":
				cloumn = "s_loc_zone";
				break;
			case "sLocLocationNames":
				cloumn = "s_loc_location_name";
				break;
			case "dLocZone1s":
				cloumn = "d_loc_zone1";
				break;
			case "dLocZone2s":
				cloumn = "d_loc_zone2";
				break;
			case "dLocZone3s":
				cloumn = "d_loc_zone3";
				break;
			case "attribute20s":
				cloumn = "attribute20";
				break;
			case "stdModelGroup1s":
				cloumn = "std_model_group1";
				break;
			default:
				return null;
		}
		return cloumn;
	}


	@Override
	public List<Object> selectAllProperty(String type) {
		String cloumn = spropertyToCloumnName(type);
		if (!Strings.isNullOrEmpty(cloumn)) {
			EntityWrapper<StaPrice> staPriceEntityWrapper = new EntityWrapper<>();
			staPriceEntityWrapper.isNotNull(cloumn);
			staPriceEntityWrapper.groupBy(cloumn);
			staPriceEntityWrapper.setSqlSelect(cloumn);
			return selectObjs(staPriceEntityWrapper);
		}
		return null;
	}

	/**
	 * 获取标准价同步数据中的起运地
	 *
	 * @return
	 */
	@Override
	public List<Object> selectAllStaPriceStartLoctionName() {
		EntityWrapper<StaPrice> staPriceEntityWrapper = new EntityWrapper<>();
		staPriceEntityWrapper.isNotNull("s_loc_location_name");
		staPriceEntityWrapper.groupBy("s_loc_location_name");
		staPriceEntityWrapper.setSqlSelect("s_loc_location_name");
		return selectObjs(staPriceEntityWrapper);
	}

	/**
	 * 查询标准价同步数据
	 *
	 * @param condition
	 * @return
	 */
	@Override
	public List<StaPrice> selectStaPriceList(Map<String, Object> condition) {
//		List<StaPrice> staPrices = null;
		EntityWrapper<StaPrice> staPriceEntityWrapper = this.bindStaPriceWrapper(condition);
		return selectList(staPriceEntityWrapper);
//		if (!CollectionUtils.isEmpty(staPrices = selectList(staPriceEntityWrapper))) {
//			return staPrices;
//		} else {
//			if (condition.containsKey("dLocZone1") && condition.containsKey("dLocZone2") && condition.containsKey("dLocZone3") && condition.containsKey("dLocLocationName")) {
//				HashMap<String, Object> removeDlocZoneNameMap = new HashMap<>(condition);
//				if (!StringUtils.isEmpty(condition.get("dLocLocationName"))) {
//					removeDlocZoneNameMap.put("dLocLocationName", "");
//					EntityWrapper<StaPrice> removeDLocEw = this.bindStaPriceWrapper(removeDlocZoneNameMap);
//					if (!CollectionUtils.isEmpty(staPrices = selectList(removeDLocEw))) {
//						return staPrices;
//					}
//				}
//				if (!StringUtils.isEmpty(condition.get("dLocZone3"))) {
//					removeDlocZoneNameMap.put("dLocZone3", "");
//					EntityWrapper<StaPrice> removeDLocEw = this.bindStaPriceWrapper(removeDlocZoneNameMap);
//					if (!CollectionUtils.isEmpty(staPrices = selectList(removeDLocEw))) {
//						return staPrices;
//					}
//				}
//			}
//			if (condition.containsKey("sLocZone") && condition.containsKey("sLocZone3") && condition.containsKey("sLocLocationName")) {
//				if (!StringUtils.isEmpty(condition.get("sLocLocationName"))) {
//					condition.put("sLocLocationName", "");
//					if (!CollectionUtils.isEmpty(staPrices = this.selectStaPriceList(condition))) {
//						return staPrices;
//					}
//				}
//				if (!StringUtils.isEmpty(condition.get("sLocZone3"))) {
//					condition.put("sLocZone3", "");
//					if (!CollectionUtils.isEmpty(staPrices = this.selectStaPriceList(condition))) {
//						return staPrices;
//					}
//				}
//			}
//			return staPrices;
//		}
	}


	/**
	 * 根据属性值寻找批量匹配标准价同步数据
	 *
	 * @param staPriceItemProperty
	 * @return
	 */
	@Override
	@Deprecated
	public List<StaPrice> selectStaPriceListByProperty(List<StaPrice> staPriceItemProperty) {
		List<StaPrice> returnStaPrice = new ArrayList<>();
		if (CollectionUtils.isEmpty(staPriceItemProperty)) {
			return returnStaPrice;
		}
		/*
		 * 遍历同步数据
		 */
		for (StaPrice staPriceItem :
				staPriceItemProperty) {
			returnStaPrice.add(this.selectStaPriceByProperty(staPriceItem, null));
		}
		return returnStaPrice;
	}

	/**
	 * 根据属性值寻找批量匹配标准价同步数据
	 *
	 * @param staPriceItemProperty
	 * @return
	 */
	@Override
	public List<StaPriceAndQuoteDtlVO> selectStaPriceVOListByProperty(List<StaPriceAndQuoteDtlVO> staPriceItemProperty, Map<String, Object> condition) {
		List<StaPriceAndQuoteDtlVO> returnStaPrice = new ArrayList<>();
		if (CollectionUtils.isEmpty(staPriceItemProperty)) {
			return returnStaPrice;
		}

		List<Long> feeIds = new ArrayList<>();
		staPriceItemProperty.forEach(staPriceAndQuoteDtlVO -> {
			feeIds.add(staPriceAndQuoteDtlVO.getFeeId());
		});

		List<FeePayable> feePayables = feePayableService.selectBatchIds(feeIds);
		Map<Long, Long> feeIdAndStaIdMap = new HashMap<>();
		feePayables.forEach(feePayable -> {
			OtmServiceResult stdPrice = otmUtil.getStdPrice(feePayable.getWaybillDtlId());
			if ("200".equals(stdPrice.getMessageCode())) {
				if (!StringUtils.isEmpty(stdPrice.getData())) {
					JSONObject.parseObject(stdPrice.getData());
					Map<String, Object> data =  JSONObject.parseObject(stdPrice.getData(), Map.class);
					if (!CollectionUtils.isEmpty(data)) {
						Object id = data.get("id");
						feePayable.setStaPriceId((id == null) ? null : Long.parseLong(id.toString()));
						//Object price = data.get("price");
						//feePayable.setEstPrice((price == null) ? null : new BigDecimal(price.toString()));
						//Object miles = data.get("miles");
						//feePayable.setKilometre((miles == null) ? null : new BigDecimal(miles.toString()));
					} else {
						feePayable.setStaPriceId(null);
						feePayable.setEstPrice(BigDecimal.ZERO);
						feePayable.setKilometre(BigDecimal.ZERO);
					}
				}
				//Map<String, Object> data = stdPrice.getData();
			}
			feeIdAndStaIdMap.put(feePayable.getId(), feePayable.getStaPriceId());
		});
		/*
		 * 遍历同步数据
		 */
		for (StaPriceAndQuoteDtlVO staPriceItem :
				staPriceItemProperty) {
			Long staPriceId = feeIdAndStaIdMap.get(staPriceItem.getFeeId());
			if (staPriceId != null) {
				Map<String, Object> seachCondition = new HashMap<>();
				seachCondition.put("id", staPriceId);
				StaPrice bindToStaPrice = this.selectStaPriceByProperty(null, seachCondition);
				if (bindToStaPrice != null) {
					BeanUtils.copyProperties(bindToStaPrice, staPriceItem);
				}
			}
			returnStaPrice.add(staPriceItem);
//			if (staPriceItem.getEffectiveDate() != null) {
//				seachCondition.put("effectiveDate", staPriceItem.getEffectiveDate());
//			}
			//if (!CollectionUtils.isEmpty(condition)) {
			//	seachCondition.putAll(condition);
			//}
//			StaPrice staPrice = new StaPrice();
//			BeanUtils.copyProperties(staPriceItem, staPrice);
//			String carService = amgCstService.getCarServiceByVehicelName(staPrice.getStdModelGroup1(), staPrice.getTransportNodeGid(), staPrice.getAttribute20());
//			if (!StringUtils.isEmpty(carService)) {
//				staPrice.setStdModelGroup1(carService);
//			}
//			if (!Strings.isNullOrEmpty(staPrice.getTransportNodeGid())) {
//				if (!CollectionUtils.isEmpty(transTypeNameContrastService.selectTransTypeNamesByTypeName(staPrice.getTransportNodeGid()))) {
//					staPrice.setTransportNodeGid(null);
//				}
//			}
//			if (Strings.isNullOrEmpty(staPrice.getsLocLocationName())) {
//				seachCondition.put("sLocLocationName", "");
//			}
//			if (Strings.isNullOrEmpty(staPrice.getdLocLocationName())) {
//				seachCondition.put("dLocLocationName", "");
//			}
//			if (Strings.isNullOrEmpty(staPrice.getsLocZone())) {
//				seachCondition.put("sLocZone", "");
//			}
//			if (Strings.isNullOrEmpty(staPrice.getsLocZone3())) {
//				seachCondition.put("sLocZone3", "");
//			}
//			if (Strings.isNullOrEmpty(staPrice.getdLocZone1())) {
//				seachCondition.put("dLocZone1", "");
//			}
//			if (Strings.isNullOrEmpty(staPrice.getdLocZone2())) {
//				seachCondition.put("dLocZone2", "");
//			}
//			if (Strings.isNullOrEmpty(staPrice.getdLocZone3())) {
//				seachCondition.put("dLocZone3", "");
//			}
		}
		feePayableService.updateBatchById(feePayables);
		return returnStaPrice;
	}

	/**
	 * 根据属性值寻找匹配标准价同步数据
	 *
	 * @param staPriceProperty
	 * @param addCondition
	 * @return
	 */
	@Override
	public StaPrice selectStaPriceByProperty(StaPrice staPriceProperty, Map<String, Object> addCondition) {
		Map<String, Object> itemPropertyMapping;
		if (staPriceProperty == null) {
			itemPropertyMapping = new HashMap<>();
		} else {
			itemPropertyMapping = BeanColumnUtil.objectToMap(staPriceProperty);
		}
//		itemPropertyMapping.put("queryTransModelFlag", 1);
		itemPropertyMapping.remove("id");
		itemPropertyMapping.remove("serialVersionUID");
		if (!CollectionUtils.isEmpty(addCondition)) {
			if (addCondition.containsKey("remove")) {
				Object remove = addCondition.remove("remove");
				if (remove != null) {
					List removeItem = (ArrayList) remove;
					for (Object item :
							removeItem) {
						itemPropertyMapping.remove(item);
					}
				}
			}
			itemPropertyMapping.putAll(addCondition);
		}
		if (!CollectionUtils.isEmpty(itemPropertyMapping)) {
			StringBuffer msg = new StringBuffer();

			/*
			 * 验证匹配结果
			 */
			List<StaPrice> staPrices = this.selectStaPriceList(itemPropertyMapping);
			if (CollectionUtils.isEmpty(staPrices)) {
				if (staPriceProperty == null) {
					return null;
				}
				if (staPriceProperty.getPrice() == null) {
					staPriceProperty.setPrice(BigDecimal.ZERO);
				}
				if (staPriceProperty.getContractMiles() == null) {
					staPriceProperty.setContractMiles(BigDecimal.ZERO);
				}
				return staPriceProperty;
			} else if (staPrices.size() > 1) {
				throw new BaseException("匹配重复标准价数据，请核实！");
			} else {
				return staPrices.get(0);
			}
		}
		return staPriceProperty;
	}

	private EntityWrapper<StaPrice> bindStaPriceWrapper(Map<String, Object> condition) {
		EntityWrapper<StaPrice> staPriceEntityWrapper = new EntityWrapper<>();

		/*
		 * 特殊统配方式
		 */
//		Object transportNodeGid = condition.get("transportNodeGid");
//		if (StringUtils.isEmpty(transportNodeGid)) {
//			if (Objects.deepEquals(1, condition.get("queryTransModelFlag"))) {
//				staPriceEntityWrapper.isNull("transport_node_gid");
//			}
//		} else {
//			if (BaseEnum.BASE_TRANS_MODEL.getName().equals(transportNodeGid)) {
//				staPriceEntityWrapper.isNull("transport_node_gid");
//			} else {
//				staPriceEntityWrapper.eq("transport_node_gid", transportNodeGid);
//			}
//		}
		/*
		 * 默认统配方式
		 */
		if (!CollectionUtils.isEmpty(condition)) {
			List<String> areNullList = new ArrayList<>();

			for (Map.Entry<String, Object> item :
					condition.entrySet()) {
				if (!StringUtils.isEmpty(item.getValue())) {
					String cloumn = spropertyToCloumnName(item.getKey());
					if (!Strings.isNullOrEmpty(cloumn)) {
						staPriceEntityWrapper.in(cloumn, JSONArray.parseArray(JSONArray.toJSONString(item.getValue())));
					}
					if ("id".equals(item.getKey())) {
						staPriceEntityWrapper.eq("id", item.getValue());
					}
					if ("attribute20".equals(item.getKey())) {
						staPriceEntityWrapper.eq("attribute20", item.getValue());
					}
					if ("stdModelGroup1".equals(item.getKey())) {
						staPriceEntityWrapper.eq("std_model_group1", item.getValue());
					}
					if ("startDateS".equals(item.getKey())) {
						// staPriceEntityWrapper.ge("start_date", item.getValue());
						staPriceEntityWrapper.le("start_date", item.getValue());
					}
					if ("startDateE".equals(item.getKey())) {
						// staPriceEntityWrapper.le("start_date", item.getValue());
						staPriceEntityWrapper.ge("expire_date", item.getValue());
					}
					if ("effectiveDate".equals(item.getKey())) {
						staPriceEntityWrapper.le("start_date", item.getValue());
						staPriceEntityWrapper.ge("expire_date", item.getValue());
					}
					if ("transportNodeGid".equals(item.getKey())){
						if (BaseEnum.BASE_TRANS_MODEL.getName().equals(item.getValue())) {
							staPriceEntityWrapper.isNull("transport_node_gid");
						} else {
							staPriceEntityWrapper.eq("transport_node_gid", item.getValue());
						}
					}

				}
			}

			if (condition.containsKey("sLocZone")) {
				Object sLocZone1 = condition.get("sLocZone");
				if (StringUtils.isEmpty(sLocZone1)) {
					areNullList.add("s_loc_zone");
				} else {
					staPriceEntityWrapper.eq("s_loc_zone", sLocZone1);
				}
			}
			if (condition.containsKey("sLocZone3")) {
				Object sLocZone3 = condition.get("sLocZone3");
				if (StringUtils.isEmpty(sLocZone3)) {
					areNullList.add("s_loc_zone3");
//					staPriceEntityWrapper.andNew().isNull("s_loc_zone3").or().eq("s_loc_zone3", "");
				} else {
					staPriceEntityWrapper.eq("s_loc_zone3", sLocZone3);
				}
			}
			if (condition.containsKey("sLocLocationName")) {
				Object sLocLocationName = condition.get("sLocLocationName");
				if (StringUtils.isEmpty(sLocLocationName)) {
					areNullList.add("s_loc_location_name");
//					staPriceEntityWrapper.andNew().isNull("s_loc_location_name").or().eq("s_loc_location_name", "");
				} else {
					staPriceEntityWrapper.eq("s_loc_location_name", sLocLocationName);
				}
			}

			if (condition.containsKey("dLocZone1")) {
				Object dLocZone1 = condition.get("dLocZone1");
				if (StringUtils.isEmpty(dLocZone1)) {
					areNullList.add("d_loc_zone1");
//					staPriceEntityWrapper.andNew().isNull("d_loc_zone1").or().eq("d_loc_zone1", "");
				} else {
					staPriceEntityWrapper.eq("d_loc_zone1", dLocZone1);
				}
			}
			if (condition.containsKey("dLocZone2")) {
				Object dLocZone2 = condition.get("dLocZone2");
				if (StringUtils.isEmpty(dLocZone2)) {
					areNullList.add("d_loc_zone2");
//					staPriceEntityWrapper.andNew().isNull("d_loc_zone2").or().eq("d_loc_zone2", "");
				} else {
					staPriceEntityWrapper.eq("d_loc_zone2", dLocZone2);
				}
			}
			if (condition.containsKey("dLocZone3")) {
				Object dLocZone3 = condition.get("dLocZone3");
				if (StringUtils.isEmpty(dLocZone3)) {
					areNullList.add("d_loc_zone3");
//					staPriceEntityWrapper.andNew().isNull("d_loc_zone3").or().eq("d_loc_zone3", "");
				} else {
					staPriceEntityWrapper.eq("d_loc_zone3", dLocZone3);
				}
			}
			if (condition.containsKey("dLocLocationName")) {
				Object dLocLocationName = condition.get("dLocLocationName");
				if (StringUtils.isEmpty(dLocLocationName)) {
					areNullList.add("d_loc_location_name");
//					staPriceEntityWrapper.andNew().isNull("d_loc_location_name").or().eq("d_loc_location_name", "");
				} else {
					staPriceEntityWrapper.eq("d_loc_location_name", dLocLocationName);
				}
			}

			Object isNullItem = condition.get("isNull");
			if (!StringUtils.isEmpty(isNullItem)) {
				String[] split = (String[]) isNullItem;
				if (!ArrayUtils.isEmpty(split)) {
					areNullList.addAll(Arrays.asList(split));
				}
			}
			if (!CollectionUtils.isEmpty(areNullList)) {
				for (String item :
						areNullList) {
					if (!StringUtils.isEmpty(item)) {
						staPriceEntityWrapper.andNew().isNull(item).or().eq(item, "");
					}
				}
			}
		}
		return staPriceEntityWrapper;
	}
}
